package com.shiku.mianshi.controller;

import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.constants.KConstants.*;
import cn.xyz.commons.ex.ServiceException;
import cn.xyz.commons.utils.OtpHelper;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.mianshi.model.KSession;
import cn.xyz.mianshi.model.PageResult;
import cn.xyz.mianshi.service.impl.AuthKeysServiceImpl;
import cn.xyz.mianshi.service.impl.PayServiceImpl;
import cn.xyz.mianshi.utils.SKBeanUtils;
import cn.xyz.mianshi.vo.ConsumeRecord;
import cn.xyz.mianshi.vo.PayInfo;
import cn.xyz.mianshi.vo.PayScoreInfo;
import cn.xyz.mianshi.vo.User;
import cn.xyz.service.AuthServiceOldUtils;
import cn.xyz.service.AuthServiceUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shiku.utils.Base64;
import com.shiku.utils.encrypt.AES;
import com.wxpay.utils.GetWxOrderno;
import com.wxpay.utils.MD5Util;
import com.wxpay.utils.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 
 * @Description: TODO(支付收款相关)
 * @author zhm
 * @date 2019年2月16日 下午6:08:53
 * @version V1.0
 */


@RestController
@Api(value="PayController",tags="支付收款相关")
@RequestMapping(value="/pay",method={RequestMethod.GET,RequestMethod.POST})
public class PayController extends AbstractController{
	
	@Autowired
	private PayServiceImpl payService;
	@Autowired
	private AuthKeysServiceImpl authKeysService;

	/**
	 * 条码、付款码支付(付款)
	 * @param paymentCode
	 * @param money
	 * @param secret
	 * @return
	 */
	@ApiOperation("条码、付款码支付(付款)")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "paymentCode",value = "付款码",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "money",value = "付款金额",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "time",value = "时间",dataType = "long",required = true,defaultValue = "0"),
			@ApiImplicitParam(paramType = "query",name = "desc",value = "详情",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "secret",value = "加密字符",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "salt",value = "盐加密",dataType = "String",required = true)
	})
	@RequestMapping(value = "/codePayment")
	public JSONMessage codePayment(@RequestParam(defaultValue="") String paymentCode,@RequestParam(defaultValue="") String money,
			@RequestParam(defaultValue="0") long time,@RequestParam(defaultValue="") String desc,@RequestParam(defaultValue="") String secret,String salt){
		if(true){
			return JSONMessage.failureByErrCode(ResultCode.PleaseUpgradeLatestVersion);
		}
		// 解析付款码
		Integer fromUserId=payService.analysisCode(paymentCode);
		if(fromUserId==null){
			return JSONMessage.failureByErrCode(PayResultCode.PayCodeWrong);
		}
		// 校验付款码唯一性
		if(payService.checkPaymentCode(fromUserId, paymentCode)){
			return JSONMessage.failureByErrCode(PayResultCode.PayCodeExpired);
		}
		Integer userId=ReqUtil.getUserId();
		// 不支持向自己付款
		if(userId.equals(fromUserId)){
			return JSONMessage.failureByErrCode(PayResultCode.NotPayWithSelf);
		}

		if(userId.equals(fromUserId)){
			return JSONMessage.failureByErrCode(PayResultCode.NotPayWithSelf);
		}
		if(StringUtil.isEmpty(salt)){
			// 校验加密规则
			if(!AuthServiceOldUtils.authPaymentCode(paymentCode, userId.toString(), money, getAccess_token(), time, secret)){
				return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
			}
		}

		try {
				// 用户金额操作
				payService.paymentCodePay(paymentCode,userId, fromUserId, money,desc);
				return JSONMessage.success();
			} catch (Exception e) {
				e.printStackTrace();
				return JSONMessage.error(e);
			}
			
		
	}



	/**
	 * 二维码收款设置金额
	 * @param money
	 * @return
	 */
	@ApiOperation("二维码收款设置金额")
	@ApiImplicitParam(paramType = "query",name = "money",value = "设置金额",dataType = "String",required = true)
	@RequestMapping(value = "/setMoney")
	public JSONMessage setMoney(@RequestParam(defaultValue="") String money){

		return null;
		
	}
	
	/**
	 * 二维码收款
	 * @param toUserId 收款人（金钱增加）
	 * @param money
	 * @param secret
	 * @return
	 */
	@ApiOperation("二维码收款")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "toUserId",value = "目标用户编号",dataType = "int",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "money",value = "付款金额",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "time",value = "时间",dataType = "long",required = true,defaultValue = "0"),
			@ApiImplicitParam(paramType = "query",name = "desc",value = "详情",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "secret",value = "加密字符",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "salt",value = "盐加密",dataType = "String",required = true)
	})
	@RequestMapping(value = "/codeReceipt")
	public JSONMessage codeTransfer(@RequestParam(defaultValue="") Integer toUserId,@RequestParam(defaultValue="") String money,@RequestParam(defaultValue="0") long time,
			@RequestParam(defaultValue="") String desc,@RequestParam(defaultValue="") String secret,String salt){
		if(true){
			return JSONMessage.failureByErrCode(ResultCode.PleaseUpgradeLatestVersion);
		}
		Integer userId=ReqUtil.getUserId();
		if(userId.equals(toUserId)){
			return JSONMessage.failureByErrCode(PayResultCode.NotPayWithSelf);
		}
		String token=getAccess_token();
		String payPassword = authKeysService.getPayPassword(userId);
		if(StringUtil.isEmpty(salt)){
			// 校验加密规则
			if(!AuthServiceOldUtils.authQRCodeReceipt(userId.toString(), token, money, time,payPassword,secret)){
				return JSONMessage.failureByErrCode(PayResultCode.PayPasswordNotExist);
			}
		}


		try {
			payService.receipt(userId, toUserId, money,desc);
			return JSONMessage.success();
		} catch (Exception e) {
			e.printStackTrace();
			return JSONMessage.failureByException(e);
		}
	}
	
	/**
	 * 二维码收款

	 * @return
	 */
	@ApiOperation("二维码收款")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "codeId",value = "编号",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "data",value = "付款金额",dataType = "String",required = true,defaultValue = "")
	})
	@RequestMapping(value = "/codeReceipt/v1")
	public JSONMessage codeTransferV1(@RequestParam(defaultValue="") String codeId,@RequestParam(defaultValue="") String data){
		Integer userId=ReqUtil.getUserId();
		
		String token=getAccess_token();
		String payPassword = authKeysService.getPayPassword(userId);

		// 校验加密规则
		JSONObject jsonObject = AuthServiceUtils.authQrCodeTransfer(userId, token, data, codeId,payPassword);
		if(null==jsonObject) 
			return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
		Integer toUserId = jsonObject.getInteger("toUserId");
		if(userId.equals(toUserId)){
			return JSONMessage.failureByErrCode(PayResultCode.NotPayWithSelf);
		}
		
		try {
			payService.receipt(userId,jsonObject.getInteger("toUserId")
					,jsonObject.getString("money"),jsonObject.getString("desc"));
			return JSONMessage.success();
		} catch (Exception e) {
			e.printStackTrace();
			return JSONMessage.failureByException(e);
		}
	}
	
	/**
	 * 统一下单接口
	 * appId
	 * body 商品描述
	 * input_charset 编码格式
	 * nonce_str 随机生成的数
	 * notify_url 回调的url
	 * sign 签名
	 * spbill_create_ip 请求的Ip
	 * total_fee 总费用
	 * trade_no 交易订单
	 * trade_type 交易类型：APP,WEB
	 * @return prepayId
	 */
	@ApiOperation("统一下单接口")
	@RequestMapping(value = "/unifiedOrder")
	public JSONMessage unifiedOrder(HttpServletRequest request,HttpServletResponse response){
		try {
			 Map<String, String> map = null;
			 java.util.Enumeration<String>  enums=request.getParameterNames();
			 while(enums.hasMoreElements()){    
                 String  paramName=(String)enums.nextElement();                        
                 map=GetWxOrderno.doXMLParse(paramName); 
			 }  
			JSONMessage data = payService.unifiedOrderImpl(map);
			return data;
		} catch (Exception e) {
			return JSONMessage.failureByException(e);
		}
	}
	@ApiOperation("统一下单接口")
	@RequestMapping(value = "/createOrder")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "appId",value = "appID",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "nonce_str",value = "随机生成的数",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "body",value = "描述",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "trade_no",value = "交易订单号",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "total_fee",value = "交易总金额",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "notify_url",value = "回调地址",dataType = "String",required = true),
			@ApiImplicitParam(paramType = "query",name = "sign",value = "签名",dataType = "String",required = true),
	})
	public JSONMessage unifiedOrderEx(@RequestParam(defaultValue="") String appId,@RequestParam(defaultValue="") String nonce_str,
									  @RequestParam(defaultValue="") String body,
									  @RequestParam(defaultValue="") String trade_no, @RequestParam(defaultValue="") String total_fee,
									  @RequestParam(defaultValue="") String notify_url, @RequestParam(defaultValue="") String sign )
	{
		Map<String, String> map =  new HashMap<>();
		map.put("appId",appId);
		map.put("nonce_str",nonce_str);
		map.put("body",body);
		map.put("trade_no",trade_no);
		map.put("total_fee",total_fee);
		map.put("notify_url",notify_url);
		map.put("sign",sign);
		JSONMessage data = payService.unifiedOrderExImpl(map);
		return data;
	}

	@ApiOperation("调用第三方支付")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query",name = "payType",value = "支付类型",dataType = "String",required = true),
		@ApiImplicitParam(paramType = "query",name = "amount",value = "支付金额",dataType = "Double",required = true)
	})
	@RequestMapping(value = "/gotoPay")
	public JSONMessage gotoPay(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(defaultValue="")String payType,@RequestParam(defaultValue="0.0")Double amount)
	{
		//生成单号等信息保存到数据库
		Integer userId = ReqUtil.getUserId();
		String requestIp = getRequestIp(); //获取注册用户ip地址
		return 	payService.paySdkOrderImpl(userId, payType, amount,requestIp,response);
	}
	@ApiOperation("亿乐回调接口")
	@RequestMapping(value = "/ylcallback")
	public String YL_Callback(HttpServletRequest request,HttpServletResponse response)
	{
//		String _postValue = "";
//		try {
//			_postValue = getRequestPostStr(request);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		logger.info("[ww]=YL_Callback=_postValue="+_postValue);
//		JSONObject jsonObject = JSON.parseObject(_postValue);
//		
		SortedMap<String,String> params = new TreeMap<String,String>();
//		params.put("callbacks", jsonObject.getString("callbacks"));
//		params.put("appid", jsonObject.getString("appid"));
//		params.put("pay_type", jsonObject.getString("pay_type"));
//		params.put("success_url", jsonObject.getString("success_url"));
//		params.put("error_url", jsonObject.getString("error_url"));
//		params.put("out_trade_no", jsonObject.getString("out_trade_no"));
//		params.put("amount", jsonObject.getString("amount"));
//		params.put("sign", jsonObject.getString("sign"));
//		params.put("amount_true", jsonObject.getString("amount_true"));
//		params.put("out_uid", jsonObject.getString("out_uid"));
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		    String name = (String) iter.next();
		    String[] values = (String[]) requestParams.get(name);
		    String valueStr = "";
		    for (int i = 0; i < values.length; i++) {
		        valueStr = (i == values.length - 1) ? valueStr + values[i]
		                    : valueStr + values[i] + ",";
		  	}
			params.put(name, valueStr);
		}
		if(params.containsKey("callbacks") && params.get("callbacks").equals("CODE_SUCCESS") )
		{
			if(!payService.checkSignV1(params, params.get("sign")))
			{
				logger.info("[ww]==签名校验失败==");
				return "error";
			}
		
			payService.AddMoeny(params.get("out_trade_no"));
			logger.info("[ww]==亿乐充值成功==");
			return "success";
		}
		logger.info("[ww]==亿乐充值失败==");
		return "error";
	}
	@ApiOperation("pg回调接口")
	@RequestMapping(value = "/pgcallback")
	public String Pg_CallBack(HttpServletRequest request,HttpServletResponse response)
	{
		JSONObject notifyJson = getRequestParams(request);
		Boolean  pass = payService.verifySign(notifyJson); 
		 if (pass) {
			 if ("00".equals(notifyJson.getString("code"))) {
	                // 成功操作，需要判断该订单状态是否已更改成功，避免订单重复操作
				 	payService.AddMoeny(notifyJson.getString("orderNum"));
	             }
		 }
		 else {
             return "verify sign failed";
         }
		 return "SUCCESS";
	}
	  private  JSONObject getRequestParams(HttpServletRequest request) {
	        Map map = new HashMap();
	        Enumeration<String> it = request.getParameterNames();
	        while (it.hasMoreElements())
	        {
	            String name = it.nextElement();
	            String value = request.getParameter(name);
	            value = (StringUtils.isBlank(value)) || (value.equals("null")) ? "" : value;
	            map.put(name, value);
	        }
	        return JSONObject.parseObject(JSON.toJSONString(map));
	    }
	
	 public  String getRequestPostStr(HttpServletRequest request)
	            throws IOException {
	        byte buffer[] = getRequestPostBytes(request);
	        String charEncoding = request.getCharacterEncoding();
	        if (charEncoding == null) {
	            charEncoding = "UTF-8";
	        }
	        return new String(buffer, charEncoding);
	    }
	 
	  public  byte[] getRequestPostBytes(HttpServletRequest request)
	            throws IOException {
	        int contentLength = request.getContentLength();
	        if(contentLength<0){
	            return null;
	        }
	        byte buffer[] = new byte[contentLength];
	        for (int i = 0; i < contentLength;) {
	 
	            int readlen = request.getInputStream().read(buffer, i,
	                    contentLength - i);
	            if (readlen == -1) {
	                break;
	            }
	            i += readlen;
	        }
	        return buffer;
	  }

	/**
	 * 获取预支付订单信息

	 * @param prepayId
	 * @return
	 */
	@ApiOperation(" 获取预支付订单信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "prepayId",value = "预付编号",dataType = "String",required = true,defaultValue = "")
	})
	@RequestMapping(value = "/getOrderInfo")
	public JSONMessage getOrderInfo(@RequestParam(defaultValue="") String prepayId){
		JSONMessage data = payService.getOrderInfo(prepayId);
		return data;
	}
	
	/**
	 * 确认密码支付
	 * @param appId
	 * @param prepayId
	 * @param sign
	 * @return
	 */
	@ApiOperation("确认密码支付")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "appId",value = "编号",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "prepayId",value = "预付编号",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "sign",value = "签名",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "time",value = "时间",dataType = "long",required = true,defaultValue = "0"),
			@ApiImplicitParam(paramType = "query",name = "secret",value = "加密值",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "salt",value = "盐加密值",dataType = "String",required = true,defaultValue = "")
	})
	@RequestMapping(value = "/passwordPayment")
	public JSONMessage passwordPayment(@RequestParam(defaultValue="") String appId,@RequestParam() String prepayId,
			@RequestParam(defaultValue="") String sign,@RequestParam(defaultValue="0") long time,@RequestParam(defaultValue="") String secret,String salt){
		if(true){
			return JSONMessage.failureByErrCode(ResultCode.PleaseUpgradeLatestVersion);
		}
		Integer userId=ReqUtil.getUserId();
		String token=getAccess_token();
		JSONMessage data = payService.passwordPayment(appId,prepayId,sign,userId,token,time,secret,salt);
		return data;
	}
	/**
	 * 确认密码支付
	 * @return
	 */
	@ApiOperation("确认密码支付")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "codeId",value = "编号",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "data",value = "加密参数",dataType = "String",required = true,defaultValue = "")
	})
	@RequestMapping(value = "/passwordPayment/v1")
	public JSONMessage passwordPaymentV1(@RequestParam(defaultValue="") String codeId,@RequestParam(defaultValue="") String data){
		Integer userId=ReqUtil.getUserId();
		String token=getAccess_token();
		String payPassword = authKeysService.getPayPassword(userId);
		// 校验加密规则
		JSONObject jsonObj = AuthServiceUtils.authOrderPay(userId, token, data, codeId,payPassword);
		if(null==jsonObj)
			return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
		JSONMessage result = payService.passwordPaymentV1(jsonObj.getString("appId"),jsonObj.getString("prepayId"),
				jsonObj.getString("sign"),userId);
		return result;
	}

	/**
	 *获取二维码 支付  Key
	 * @return
	 **/
	@ApiOperation("获取二维码 支付  Key")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "codeId",value = "编号",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "data",value = "加密参数",dataType = "String",required = true,defaultValue = "")
	})
	@RequestMapping(value = "/getQrKey")
	public JSONMessage payGetQrKey(@RequestParam(defaultValue ="")String data,
								   @RequestParam(defaultValue="") String codeId) {
		int userId=ReqUtil.getUserId();
       try {
		   String code = SKBeanUtils.getRedisService().queryTransactionSignCode(userId, codeId);
		 if(StringUtil.isEmpty(code))
			   return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
		   SKBeanUtils.getRedisService().cleanTransactionSignCode(userId,codeId);
		   byte[] deCode= Base64.decode(code);
		   String payPassword = authKeysService.getPayPassword(userId);
		   JSONObject jsonObj = AuthServiceUtils.authPayGetQrKey(userId, getAccess_token(), data, deCode,payPassword);
		   if(null==jsonObj)
			   return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
			String qrKey=payService.getPayQrKey(userId);

		    qrKey= AES.encryptBase64(Base64.decode(qrKey),deCode);
		   Map<String, Object> dataMap=new HashMap<>();
		   dataMap.put("data",qrKey);
		   return JSONMessage.success(dataMap);
		} catch (ServiceException e) {
		   return JSONMessage.failureByException(e);
	   }
	}

	/**
	 *获取二维码 支付  Key
	 * @return
	 **/
	@ApiOperation("验证二维码支付Key")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "mac",value = "加密后值",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "salt",value = "盐加密值",dataType = "String",required = true,defaultValue = "")
	})
	@RequestMapping(value = "/verifyQrKey")
	public JSONMessage verifyQrKey(@RequestParam(defaultValue ="")String mac,
								   @RequestParam(defaultValue="") String salt) {
		int userId=ReqUtil.getUserId();
		try {

			String qrKey = SKBeanUtils.getRedisService().queryPayQrKey(userId);
			if(StringUtil.isEmpty(qrKey)){
					return JSONMessage.failureByErrCode(PayResultCode.PayQRKeyExpired);
			}
			byte[] deCode= Base64.decode(qrKey);


			if(!AuthServiceUtils.authPayVerifyQrKey(userId, getAccess_token(), deCode,salt,mac))
				return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
			return JSONMessage.success();
		}catch (ServiceException e) {
			return JSONMessage.failureByException(e);
		}
	}
	/**
	 * 条码、付款码支付(付款)
	 * @return
	 */
	@ApiOperation("条码、付款码支付(付款) 新版")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "salt",value = "盐加密值",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "data",value = "加密参数",dataType = "String",required = true,defaultValue = "")
	})
	@RequestMapping(value = "/codePayment/v1")
	public JSONMessage codePaymentV1(@RequestParam(defaultValue="") String data,String salt){

		int userId=ReqUtil.getUserId();
		try {
			KSession session = SKBeanUtils.getRedisService().queryUserSesson(getAccess_token());
			if(null==session){
				return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
			}
			JSONObject jsonObject = AuthServiceUtils.decodeDataToJson(data, Base64.decode(session.getPayKey()));
			if(null==jsonObject)
				return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
			String paymentCode = jsonObject.getString("paymentCode");
			String money=jsonObject.getString("money");
			if(StringUtil.isEmpty(paymentCode)||StringUtil.isEmpty(money)){
				return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
			}

			OtpHelper.QrCode qrCode = OtpHelper.parse(paymentCode);
			if(userId==qrCode.getUserId()){
				return JSONMessage.failureByErrCode(PayResultCode.NotPayWithSelf);
			}
			// 校验付款码唯一性
			if(payService.checkPaymentCode(qrCode.getUserId(), paymentCode)){
				return JSONMessage.failureByErrCode(PayResultCode.PayCodeExpired);
			}
			String apiKey = SKBeanUtils.getLocalSpringBeanManager().getAppConfig().getApiKey();
			String qrKey = SKBeanUtils.getRedisService().queryPayQrKey(qrCode.getUserId());
			if(StringUtil.isEmpty(qrKey)){
				return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
			}
			byte[] decode = Base64.decode(qrKey);
			long time=System.currentTimeMillis()/60000;
			long otp = OtpHelper.otp(apiKey, qrCode.getUserId(), time, decode,qrCode.getRandByte());
			if(qrCode.getOtp()!=otp){
				otp = OtpHelper.otp(apiKey, qrCode.getUserId(), time-1, decode,qrCode.getRandByte());
				if(qrCode.getOtp()!=otp){
					otp = OtpHelper.otp(apiKey, qrCode.getUserId(), time+1, decode,qrCode.getRandByte());
					if(qrCode.getOtp()!=otp){
						return JSONMessage.failureByErrCode(ResultCode.AUTH_FAILED);
					}
				}
			}
			// 用户金额操作
			payService.paymentCodePay(paymentCode,userId, qrCode.getUserId(), money,"");
			return JSONMessage.success();
		} catch (Exception e) {
			return JSONMessage.failureByException(e);
		}


	}

	/**
	 * 测试程序
	 * @param money
	 * @return
	 */
	@ApiOperation("测试程序")
	@ApiImplicitParam(paramType = "query",name = "money",value = "金额",dataType = "String",required = true,defaultValue = "")
	@RequestMapping(value= "/SKPayTest")
	public JSONMessage skPayTest(@RequestParam(defaultValue="") String money){
		String totalFee= money;
		// 随机字符串
		String nonce_str = getNonceStr();
		
		SortedMap<String, String> contentMap = new TreeMap<String, String>();
		
		contentMap.put("appId", "sk96d738a743d048ad");
		contentMap.put("body", "测试APP");
		contentMap.put("input_charset", "UTF-8");
		contentMap.put("nonce_str", nonce_str);
		contentMap.put("notify_url", "http://192.168.0.168:8092/user/recharge/wxPayCallBack");
		
		contentMap.put("spbill_create_ip", "121.121.121.121");
		// 这里写的金额为1 分到时修改
		contentMap.put("total_fee", totalFee);
		contentMap.put("out_trade_no", StringUtil.getOutTradeNo());
		contentMap.put("trade_type", "WEB");
		//String sign = createSign(contentMap);
		String sign = "";
		contentMap.put("sign", sign);
		
		String xml = WXPayUtil.paramsToxmlStr(contentMap);
		String prepay_id = new GetWxOrderno().getPayNo("http://192.168.0.168:8092/pay/unifiedOrder", xml);
		System.out.println("返回数据 "+prepay_id);
		Map<String, String> map = new HashMap<>();
		map.put("prepay_id", prepay_id);
		map.put("sign", sign);
		return JSONMessage.success(map);
	}
	@ApiOperation("获取充值金额信息")
	@RequestMapping(value= "/GetPayInfo")
	public JSONMessage GetPayInfo()
	{
		PayInfo  _return = payService.getPayInfo();
		return JSONMessage.success(_return);
	}
	@ApiOperation("保存支付通道信息")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query",name = "id",value = "id",dataType = "String",required = true,defaultValue = ""),
		@ApiImplicitParam(paramType = "query",name = "isOpenAlipay",value = "是否打开支付宝",dataType = "int",required = true,defaultValue = ""),
		@ApiImplicitParam(paramType = "query",name = "isOpenBank",value = "是否打开银行卡",dataType = "int",required = true,defaultValue = ""),
		@ApiImplicitParam(paramType = "query",name = "isOpenWechat",value = "是否打开微信",dataType = "int",required = true,defaultValue = "")
})
	@RequestMapping(value= "/SavePayInfo")
	public JSONMessage SavePayInfo(String id,int isOpenAlipay,int isOpenBank,int isOpenWechat)
	{
		payService.SavePayInfo(id, isOpenAlipay, isOpenBank, isOpenWechat);
		return JSONMessage.success();
	}
	@ApiOperation("保存支付金额信息")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query",name = "id",value = "id",dataType = "String",required = true,defaultValue = ""),
		@ApiImplicitParam(paramType = "query",name = "PricValue",value = "金额",dataType = "int",required = true,defaultValue = ""),
		@ApiImplicitParam(paramType = "query",name = "Status",value = "状态",dataType = "int",required = true,defaultValue = ""),
		@ApiImplicitParam(paramType = "query",name = "PayChannel",value = "通道",dataType = "int",required = true,defaultValue = "")
})
	@RequestMapping(value= "/SavePayScoreInfo")
	public JSONMessage SavePayScoreInfo(String id,int PricValue,int Status,int PayChannel)
	{
		payService.SavePayScore(id, PricValue, Status, PayChannel);
		return JSONMessage.success();
	}
	/**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
//	public static String createSign(SortedMap<String, String> packageParams) {
//		StringBuffer sb = new StringBuffer();
//		Set es = packageParams.entrySet();
//		Iterator it = es.iterator();
//		while (it.hasNext()) {
//			Map.Entry entry = (Map.Entry) it.next();
//			String k = (String) entry.getKey();
//			String v = (String) entry.getValue();
//			if (null != v && !"".equals(v) && !"sign".equals(k)
//					&& !"key".equals(k)) {
//				sb.append(k + "=" + v + "&");
//				//System.out.println(k+"----"+v);
//			}
//		}
////		sb.append("key=" + this.getKey());
//		//System.out.println("key====="+this.getKey());
//		String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8")
//				.toUpperCase();
//		return sign;
//
//	}
//
	
	
	/**
	 * 获取随机字符串
	 * @return
	 */
	public static String getNonceStr() {
		// 随机数
		String currTime = getCurrTime();
		// 8位日期
		String strTime = currTime.substring(5, currTime.length());
		// 四位随机数
		String strRandom = buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		return strTime + strRandom;
	}
	

	/**
	 * 获取当前时间 yyyyMMddHHmmss
	 * @return String
	 */ 
	public static String getCurrTime() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String s = outFormat.format(now);
		return s;
	}
	
	/**
	 * 取出一个指定长度大小的随机正整数.
	 * 
	 * @param length
	 *            int 设定所取出随机数的长度。length小于11
	 * @return int 返回生成的随机数。
	 */
	public static int buildRandom(int length) {
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < length; i++) {
			num = num * 10;
		}
		return (int) ((random * num));
	}
}
